//
//  LatestViewController.m
//  YiShangPin
//
//  Created by 衣尚品1 on 15/3/5.
//  Copyright (c) 2015年 yishangpin2. All rights reserved.
//

#import "LatestViewController.h"
#import "Waterfall.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
#import "PhotoFrame.h"
#import "DetailsViewController.h"
#import "Collect.h"
#import "BuyView.h"

@interface LatestViewController (){
    AppDelegate *delegate;
    UIButton *button;
    UIButton *button1;
    NSArray *array;
    NSArray *iconImage;
    int WaterfallViewHeight;
    float AllY;
    BuyView *buyview;
    NSMutableArray *picmutArray;
    NSMutableArray *oldprice;
    NSMutableArray *newprice;
    int y;
    int y1;
    BOOL isArray1or2;
    NSString *tag;

}


@end

@implementation LatestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];


    picmutArray = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12", nil];
    oldprice = [NSMutableArray arrayWithObjects:@"168",@"129",@"200",@"234",@"321",@"157",@"123",@"453",@"290",@"310", nil];
    newprice = [NSMutableArray arrayWithObjects:@"68",@"89",@"100",@"134",@"221",@"97",@"83",@"200",@"190",@"210", nil];
    //瀑布流添加照片起始位置
    y = 0;
    y1 = 1;
    
    //瀑布流的起始位置
    WaterfallViewHeight = 280;
    
//    集成刷新控件
    [self setupRefresh];
    [self setupUpload];
    
    [self Waterfall_Upload];
    [self SmallClassify];
    
    //关闭隐藏Scrollview 的滚动条
    [self.scrollView setShowsVerticalScrollIndicator:NO];
    [self.OneScrollview setShowsHorizontalScrollIndicator:NO];
    [self.twoScrollview setShowsHorizontalScrollIndicator:NO];
    
    
    
    //注册通知  -> Waterfall.m
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Buy:) name:@"Buy" object:nil];
    

    //创建滑动选项卡
    array = [[NSArray alloc] initWithObjects:@"   Lates   ",@"   Shoes   ",@"   Dress   ",@"   Pants & Bottoms   ",@"   Bags   ",@"   Tops   ",@"   Shorts   ",@"   Watches   ",@"   Makeup & Beauty   ",@"   Jackets   ",@"   Swimsuits   ",@"   Phone Upgrades   ",@"   Sandals   ",@"   Necklaces   ",@"   Rings   ", nil];
    iconImage = [[NSArray alloc]initWithObjects:@"Lates1",@"Shoes1",@"Dress",@"Pants",@"Bags",@"Tops",@"Shorts",@"Watches",@"Makeup",@"Jackets",@"Swimsuits",@"Phone",@"Sandals",@"Necklaces",@"Rings", nil];
    [self createScrollView];
    button1 = [[UIButton alloc] init];
    
    
    
    // Do any additional setup after loading the view.
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



#pragma mark - 滑动选项卡

- (void)createScrollView{
    
    //隐藏滑动条
    [self.OneScrollview setShowsHorizontalScrollIndicator:NO];
    
    CGFloat X = 0;
    for (int i = 0; i < array.count; i++) {
        button = [[UIButton alloc] init];
        button.backgroundColor = [UIColor colorWithRed:232/255.0 green:237/255.0 blue:241/255.0 alpha:1.0];
        button.tag = 1000+i;
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
        [button setTitleColor:[UIColor blackColor] forState:0];
        //设置button的透明度
        button.alpha = 0.4;
        //设置点击后执行的事件
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        //设置button的图片
        [button setImage:[UIImage imageNamed:iconImage[i]] forState:0];
        //button长度自适应
        [button sizeToFit];
        //设置button的位置和大小
        button.frame = CGRectMake(X, 0, button.frame.size.width+10, _OneScrollview.frame.size.height);
        [self.OneScrollview addSubview:button];
        X += button.frame.size.width+3;
        
    }
    //设置scrollview滑动范围
    self.OneScrollview.contentSize = CGSizeMake(X, self.OneScrollview.frame.size.height);
}

- (void)buttonClick:(UIButton *)but{
    NSLog(@"%ld",(long)but.tag);
    button1.backgroundColor = [UIColor colorWithRed:232/255.0 green:237/255.0 blue:241/255.0 alpha:1.0];
    but.backgroundColor = [UIColor clearColor];
    button1 = but;
    [self hidenAll];
    if (but.tag == 1000) {
        //延迟0.5秒执行
        [self performSelector:@selector(showAll) withObject:nil afterDelay:1.0f];
    }
}

//隐藏所有控件
- (void)hidenAll{
    [self.scrollView headerBeginRefreshing];
    self.oneLable.hidden = YES;
    self.twoLable.hidden = YES;
    self.line.hidden = YES;
    self.twoScrollview.hidden = YES;
    self.WaterfallView.hidden = YES;
    WaterfallViewHeight = 50;
//    [self.scrollView headerEndRefreshing];
    //延迟0.5秒执行
    [self performSelector:@selector(changeHeight) withObject:nil afterDelay:1.0f];
}

//显示隐藏了的控件
- (void)showAll{
    self.oneLable.hidden = NO;
    self.twoLable.hidden = NO;
    self.line.hidden = NO;
    self.twoScrollview.hidden = NO;
    WaterfallViewHeight = 280;
    [self changeHeight];
}

- (void)changeHeight{
    self.WaterfallView.hidden = NO;
    self.WaterfallView.frame = CGRectMake(0, WaterfallViewHeight, self.view.frame.size.width, self.WaterfallView.frame.size.height);
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, AllY+WaterfallViewHeight);

}


#pragma mark - 根据图片的Tag值跳转到详情页面

-(void)Buy:(NSNotification *) tag1 {
    [self londing];
    tag = tag1.object;
    
}

#pragma mark - 请求数据
- (void)londing{
    NSURL *url = [NSURL URLWithString:[delegate.path_URL stringByAppendingString:@"ProductInfo/showproduct"]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *str = @"productId=4";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        delegate.detailsDic = arr[0];
        NSLog(@"%@",delegate.detailsDic);
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:arr waitUntilDone:YES];
        
        
        
    }];
}

- (void)refreshData:(NSArray *)sender{
    //请求完数据之后页面跳转
    DetailsViewController *details = [self.storyboard instantiateViewControllerWithIdentifier:@"Details"];
    details.photoTag = tag;
    [self.navigationController pushViewController:details animated:YES];
}

#pragma mark - 横向分类

//横向分类显示（小类）
- (void)SmallClassify{
    NSMutableArray *clothesArray = [NSMutableArray arrayWithObjects:@"fushi1.jpg",@"fushi2.jpg",@"fushi3.jpg",@"fushi4.jpg",@"fushi5.jpg",@"fushi6.jpg",@"fushi7.jpg",@"fushi8.jpg",@"fushi9.jpg",@"fushi10.jpg",@"fushi11.jpg",@"fushi12.jpg", nil];
    int l = 0;
    for (int i = 0; i<6; i++) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"photoFrame" owner:self options:nil];
        PhotoFrame *photoFrameView = nib[0];
        if (l<=9) {
            
            photoFrameView.pic1.image = [UIImage imageNamed:clothesArray[l++]];
            photoFrameView.pic2.image = [UIImage imageNamed:clothesArray[l++]];
            photoFrameView.pic3.image = [UIImage imageNamed:clothesArray[l++]];
            photoFrameView.pic4.image = [UIImage imageNamed:clothesArray[l++]];
        }
        else
        {
            l = 0;
        }
        photoFrameView.frame = CGRectMake(i*photoFrameView.frame.size.width, 0, photoFrameView.frame.size.width, photoFrameView.frame.size.height);
        [self.twoScrollview addSubview:photoFrameView];
        if (i == 5) {
            self.twoScrollview.contentSize = CGSizeMake(photoFrameView.frame.size.width * 6 , photoFrameView.frame.size.height);
        }
    }
    
    
}

#pragma mark - 瀑布流排布

//瀑布流排布商品信息
- (void)Waterfall_Upload{
    //    UIImage *image = [UIImage imageNamed:picmutArray[4]];
    
    
    for (int i = 0; i<10; i++) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"Waterfall" owner:self options:nil];
        Waterfall *waterView = nib[0];
        
        waterView.tag = 1000 + [picmutArray[i] intValue];
        //        int Y = (y<y1)?y:y1;
        //判断是左边还是右边
        int Y;
        BOOL BOOLY;
        if (y<y1) {
            BOOLY = YES;
            Y = y;
        }
        else
        { BOOLY = NO;
            Y = y1;
        }
        int X = (y<y1)?0:delegate.width/2;
        
        
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"fushi%@.jpg",picmutArray[i]]];
        //        [waterView ViewframSetX:0 SetY:0 Pic:image];
        [waterView ViewframSetX:X SetY:Y Pic:image delegateW:delegate.width];
        [waterView SetOldPrice:[oldprice[i] floatValue] SetNewPrice:[newprice[i] floatValue]];
        
        if(BOOLY)
            y += waterView.viewY;
        else
            y1 += waterView.viewY;
//        waterView.backgroundColor = [UIColor redColor];
//        waterView.alpha = 0.5;
        
        [self.WaterfallView addSubview:waterView];
        [self.scrollView addSubview:self.WaterfallView];
        
    }
    
    AllY =+ (y<y1)?y1:y;
    self.WaterfallView.frame = CGRectMake(0, WaterfallViewHeight, self.view.frame.size.width, AllY);
    self.scrollView.contentSize = CGSizeMake(delegate.width, AllY + WaterfallViewHeight);
    
    
}

#pragma mark - 上拉加载

- (void)setupUpload{
    
    // 上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.scrollView addFooterWithTarget:self action:@selector(footerRereshing)];
    
//    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    self.scrollView.footerPullToRefreshText = @"再往上拉一点!";
//    self.scrollView.footerReleaseToRefreshText = @"现在可以松开了!";
//    self.scrollView.footerRefreshingText = @"正在努力加载呢，别急~";
}

#pragma mark - 下拉刷新

- (void)setupRefresh{
    
    // 上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    
    [self.scrollView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
}

- (void)headerRereshing{
    
    //延迟0.5秒执行
    [self performSelector:@selector(stopRefresh) withObject:nil afterDelay:0.5f];
    
}

- (void)stopRefresh{
    
    [self.scrollView headerEndRefreshing];
    
}

- (void)footerRereshing{
    [self.scrollView footerEndRefreshing];
    //延迟0.5秒执行
//    [self performSelector:@selector(stopUpload) withObject:nil afterDelay:0.5f];
    NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"12",@"21",@"22", nil];

    NSMutableArray *array2 = [[NSMutableArray alloc] initWithObjects:@"11",@"10",@"22",@"17",@"7",@"6",@"19",@"4",@"3",@"16", nil];
    if (isArray1or2 == NO) {
        picmutArray = array1;
        isArray1or2 = YES;
    }
    else{
        picmutArray = array2;
        isArray1or2 = NO;
    }
    
    [self Waterfall_Upload];
    
}

- (void)stopUpload{
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Prompt" message:@"Has been to the bottom." delegate:self cancelButtonTitle:@"Ensure" otherButtonTitles:nil, nil];
    [alert show];
}

@end
